import React, { memo, useCallback, useEffect, useRef, useState } from "react";
import { useSelector, useDispatch, shallowEqual } from "react-redux";

import {
    getTopBannerAction
} from "../../store/actionCreators";

import {
    BannerWrapper,
    BannerControl,
    BannerLeft,
    BannerRight
} from "./style";
import { Carousel } from 'antd';

export default memo(function CJXTopBanner() {
    // console.log("我是 CJXTopBanner");
    //1、组件保存的状态
    const [ currentIndex, setCurrentIndex ] = useState(0);

    //2、redux 及 redux中的hook 
    const topBanners = useSelector((state) => state.getIn(["recommend", "topBanners"]), shallowEqual);
    const dispatch = useDispatch();
    // console.log(dispatch);
    //3、其他hook
    useEffect(() => {
        dispatch(getTopBannerAction())
        // console.log("CJXTopBanner轮播图的 componentDidMount生命周期函数");
    }, [dispatch])
    const bannerRef = useRef();

    //轮播图切换得得时候 得回调函数 
    const bannerChange = useCallback((from, to) => {
        setCurrentIndex(to);
        //======>>>>为啥这里打印出来的 topBanners 一直是空的，永远打印的是第一次的值。
        //======>>> useCallback传递 第二个参数 [topBanners] 则没有上面的问题？？
        // console.log(topBanners);
        // console.log(to);
    }, [])

    //4、业务逻辑
    const bgImage = topBanners[currentIndex] ? `${topBanners[currentIndex].imageUrl}?imageView&blur=40x20`: "";

    return (
        <BannerWrapper bgImage={bgImage}>
            <div className="banner wrap-v2">
                <BannerLeft>
                    <Carousel effect="fade" ref={bannerRef} autoplay beforeChange={bannerChange}>

                        {topBanners.map(item => {
                            return (
                                <div className="banner-item" key={item.targetId}>
                                    <img className="image" src={item.imageUrl} alt={item.typeTitle}></img>
                                </div>
                            )
                        })}
                        
                    </Carousel>
                </BannerLeft>
                <BannerRight></BannerRight>

                <BannerControl>
                    <button className="btn left" onClick={e => bannerRef.current.prev()}></button>
                    <button className="btn right" onClick={e => bannerRef.current.next()}></button>
                </BannerControl>

            </div>
        </BannerWrapper>
    )
})